<template>
  <div>
    <el-upload
        class="avatar-uploader"
        :action="appBaseUrl+ '/sysFile/upload'"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :on-error="handleAvatarError"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" style="max-width: 150px; height: auto">
      <div v-else class="upload-placeholder">
        <i class="el-icon-plus avatar-uploader-icon"></i>
        <div>点击上传图片</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: "ImgUpload",
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: this.value
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = res;
      this.$message.success("上传成功");
      this.$emit('input', res);
      this.$forceUpdate();
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传轮播图大小不能超过 2MB!');
      }
      return isLt2M;
    },
    handleAvatarError() {
      this.$message.error('上传失败!');
    }
  },
  watch: {
    value(val) {
      this.imageUrl = val;
    }
  }
};
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 70px;
  height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: end;
  align-items: center;
  font-size: 10px;
  color: #999;
}

.upload-placeholder .avatar-uploader-icon {
  font-size: 14px;
  font-weight: bolder;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}
</style>